All files / src/app/api/admin/promotions/[id]/codes route.ts

0% Statements 0/231
100% Branches 0/0
0% Functions 0/1
0% Lines 0/231

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from 'next/server';
import { } from "next-auth";
import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import { generateCodesSchema, promoCodeSchema } from "@/lib/promotions/validators";
import { generatePromoCodes } from "@/lib/promotions/utils";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  createdResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";

interface RouteParams {
  params: Promise<{ id: string }>;
}

/**
 * GET /api/admin/promotions/[id]/codes
 * Get all promo codes for a promotion
 */
async function handleGet(request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const promotionId = parseInt(id);

  if (isNaN(promotionId)) {
    throw ApiError.badRequest("Invalid promotion ID");
  }

  const searchParams = request.nextUrl.searchParams;
  const page = parseInt(searchParams.get("page") || "1");
  const limit = parseInt(searchParams.get("limit") || "50");
  const search = searchParams.get("search") || "";
  const status = searchParams.get("status") || ""; // "active", "inactive", "expired"

  const skip = (page - 1) * limit;

  const where: {
    promotionId: number;
    code?: { contains: string };
    isActive?: boolean;
    expiresAt?: { lt: Date } | { gte: Date } | null;
  } = { promotionId };

  if (search) {
    where.code = { contains: search.toUpperCase() };
  }

  if (status === "active") {
    where.isActive = true;
    where.expiresAt = { gte: new Date() };
  } else if (status === "inactive") {
    where.isActive = false;
  } else if (status === "expired") {
    where.expiresAt = { lt: new Date() };
  }

  const [codes, total] = await Promise.all([
    prisma.promoCode.findMany({
      where,
      include: {
        _count: { select: { usages: true } } },
      skip,
      take: limit,
      orderBy: { createdAt: "desc" } }),
    prisma.promoCode.count({ where }),
  ]);

  const now = new Date();
  const mapped = codes.map((code) => ({
    ...code,
    usageCount: code._count.usages,
    isExpired: code.expiresAt ? new Date(code.expiresAt) < now : false,
    isLimitReached: code.usageLimit ? code.usageCount >= code.usageLimit : false }));

  return successResponse({
    codes: mapped,
    pagination: {
      page,
      limit,
      total,
      pages: Math.ceil(total / limit) } });
}

/**
 * POST /api/admin/promotions/[id]/codes
 * Create a single promo code or generate batch codes
 */
async function handlePost(request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const promotionId = parseInt(id);

  if (isNaN(promotionId)) {
    throw ApiError.badRequest("Invalid promotion ID");
  }

  // Check if promotion exists
  const promotion = await prisma.promotion.findUnique({
    where: { id: promotionId } });

  if (!promotion) {
    throw ApiError.notFound("Promotion");
  }

  const body = await request.json();

  // Check if this is a batch generation request or single code creation
  if (body.count && body.count > 1) {
    // Batch generation
    body.promotionId = promotionId;
    const validationResult = generateCodesSchema.safeParse(body);

    if (!validationResult.success) {
      throw ApiError.validation("Validation failed", validationResult.error.issues);
    }

    const data = validationResult.data;

    // Generate codes
    const generatedCodes = generatePromoCodes({
      promotionId: data.promotionId,
      count: data.count,
      prefix: data.prefix,
      length: data.length,
      usageLimit: data.usageLimit ?? undefined,
      expiresAt: data.expiresAt ?? undefined });

    // Check for existing codes
    const existingCodes = await prisma.promoCode.findMany({
      where: { code: { in: generatedCodes.map((c) => c.code) } },
      select: { code: true } });

    const existingCodeSet = new Set(existingCodes.map((c) => c.code));
    const uniqueCodes = generatedCodes.filter((c) => !existingCodeSet.has(c.code));

    if (uniqueCodes.length === 0) {
      throw ApiError.conflict(
        "All generated codes already exist. Try again or use a different prefix."
      );
    }

    // Create codes in database
    await prisma.promoCode.createMany({
      data: uniqueCodes.map((code) => ({
        promotionId: code.promotionId,
        code: code.code,
        usageLimit: code.usageLimit,
        expiresAt: code.expiresAt })) });

    logger.info("Batch codes generated", { category: 'API', promotionId, count: uniqueCodes.length, skipped: generatedCodes.length - uniqueCodes.length });

    return createdResponse({
      generated: uniqueCodes.length,
      skipped: generatedCodes.length - uniqueCodes.length,
      codes: uniqueCodes.map((c) => c.code),
      message: `Generated ${uniqueCodes.length} promo codes` });
  } else {
    // Single code creation
    body.promotionId = promotionId;
    const validationResult = promoCodeSchema.safeParse(body);

    if (!validationResult.success) {
      throw ApiError.validation("Validation failed", validationResult.error.issues);
    }

    const data = validationResult.data;

    // Check if code already exists
    const existingCode = await prisma.promoCode.findUnique({
      where: { code: data.code } });

    if (existingCode) {
      throw ApiError.conflict("Promo code already exists");
    }

    const promoCode = await prisma.promoCode.create({
      data: {
        promotionId: data.promotionId,
        code: data.code,
        usageLimit: data.usageLimit,
        expiresAt: data.expiresAt } });

    logger.info("Promo code created", { category: 'API', promotionId, code: promoCode.code });

    return createdResponse(promoCode);
  }
}

/**
 * DELETE /api/admin/promotions/[id]/codes
 * Delete promo codes (bulk delete by IDs)
 */
async function handleDelete(request: NextRequest,
  context: RouteContext | undefined): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const promotionId = parseInt(id);

  if (isNaN(promotionId)) {
    throw ApiError.badRequest("Invalid promotion ID");
  }

  const body = await request.json();
  const { codeIds } = body;

  if (!codeIds || !Array.isArray(codeIds) || codeIds.length === 0) {
    throw ApiError.badRequest("codeIds array is required");
  }

  // Delete only codes that belong to this promotion
  const result = await prisma.promoCode.deleteMany({
    where: {
      id: { in: codeIds },
      promotionId } });

  logger.info("Promo codes deleted", { category: 'API', promotionId, count: result.count });

  return successResponse({
    deleted: result.count,
    message: `Deleted ${result.count} promo codes` });
}

export const GET = withErrorHandling(withAdmin(handleGet));
export const POST = withErrorHandling(withAdmin(handlePost));
export const DELETE = withErrorHandling(withAdmin(handleDelete));